import { User } from '@libs/db/models/user.model';
import { Body, Controller, Post, Req, UseGuards } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { AuthGuard } from '@nestjs/passport';
import { ApiOperation, ApiTags } from '@nestjs/swagger';
import { ReturnModelType } from '@typegoose/typegoose';
import { InjectModel } from 'nestjs-typegoose';

@ApiTags('主路由')
@Controller()
export class AppController {
  constructor(
    @InjectModel(User) private readonly userModel: ReturnModelType<typeof User>,
    private readonly jwtService: JwtService,
  ) {}

  @ApiOperation({ summary: '用户登录' })
  @UseGuards(AuthGuard('local'))
  @Post('login')
  login(@Body() user: User, @Req() request: any) {
    const payload = { _id: request.user._id };
    return {
      token: this.jwtService.sign(payload),
    };
  }

  @ApiOperation({ summary: '用户注册' })
  @Post('register')
  toRegister(@Body() user: User) {
    user.grant = 0;
    return this.userModel.create(user);
  }
}
